package org.example.config.mqtt;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.config.mqtt.property.MqttMsgContent;
import org.springframework.integration.mapping.BytesMessageMapper;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class JsonBytesMessageMapper implements BytesMessageMapper {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public byte[] fromMessage(Message<?> message) {
        try {
            MqttMsgContent<Object> mqttMsgContent = MqttMsgContent.builder()
                    .headers(message.getHeaders())
                    .payload(message.getPayload())
                    .build();
            // 将字节数组解码为 JSON 字符串并反序列化为对象
            String jsonPayload = objectMapper.writeValueAsString(mqttMsgContent);
            return jsonPayload.getBytes(StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert MQTT message to JSON", e);
        }
    }

    @Override
    public Message<?> toMessage(byte[] bytes, Map<String, Object> headers) {
        return MessageBuilder
                .withPayload(bytes)
                .copyHeadersIfAbsent(headers)
                .build();
    }
}
